<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:44:11
 * @LastEditTime: 2023-11-08 15:00:05
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description:  
 */

namespace App\Repositories;

use App\Models\Attachment;
use App\Models\TableColumn;
use ArrayAccess;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

use Illuminate\Support\Enumerable;
use Illuminate\Support\Facades\App;
use JsonSerializable;
use ReflectionClass;
use ReflectionMethod;
use Traversable;


class Repositories
    {

    protected $relation_models = [];
    protected $model;
    protected $_env_builder = null;

    public function __construct()
        {
        //注释掉，要不然del 函数 会自动删除关系
        // return App::call([$class, $A]);
        // $this->boot();
        if (method_exists($this, 'boot')) {
            App::call([$this, 'boot']);
            }
        }

    protected function setACSign($string)
        {
        $this->model->setACSign($string);
        return $this;
        }
    public function setPrefix($prefix)
        {
        $this->model->setPrefix($prefix);
        return $this;
        }

    public function setRelation(array $relation)
        {
        $this->relation_models = array_merge($this->relation_models, $relation);
        return $this;
        }
    public function getRelation()
        {
        return $this->relation_models;
        }
    public function model()
        {
        return $this->model;
        }
    public function setBuilder($builder)
        {
        $this->_env_builder = $builder;
        return $builder instanceof Builder ? $this : $this->_env_builder;
        }

    public function getBuilder() : Builder|Collection|Model
        {
        return $this->_env_builder instanceof Builder ? $this->_env_builder : $this->model->where(DB::raw('1'), 1);
        }
    public function setModel($model)
        {
        $this->model = $model;
        return $this;
        }
    public static function __callStatic($name, $arguments)
        {
        return (App::make(static::class))->$name(...$arguments);
        }

    public static function run($name, $arguments = [])
        {
        return (App::make(static::class))->$name(...$arguments);
        }
    //函数可以调用，常用的静态方法调用！
    public function isProtected($property)
        {
        if (method_exists($this, $property)) {
            $prop = new ReflectionMethod($this, $property);
            return !$prop->isPrivate() && $prop->isProtected();
            }
        return false;

        }
    public function __call($name, $arguments)
        {
        if ($this->isProtected($name)) {
            return $this->{$name}(...$arguments);
            }
        $builder = $this->getBuilder();
        //开启事务，锁定查询数据，禁止更新读
        if (in_array($name, ['get', 'first', 'find', 'autosave']) && DB::transactionLevel() > 0) {
            $builder = $builder->lockForUpdate();
            }
        return $this->setBuilder($builder->$name(...$arguments));
        }

    public function relation($query = null, $relations = null)
        {
        $query     = $query ?? $this;
        $relations = $relations ?? $this->relation_models;
        $query->with($relations);
        return $query;
        }

    public function getConditionFilter($key = '', $isremove = false)
        {
        $request = request();
        $res     = [];
        if ($request->has('filter')) {
            $filters = $request->filter;
            foreach ($request->filter as $fk => $value) {
                if (is_string($value))
                    $value = json_decode($value, true);
                foreach ($value as $k => $v) {
                    if ($k == $key) {
                        if ($isremove) {
                            unset($filters[$fk]);
                            $request->merge(['filter' => $filters]);
                            }
                        if (is_array($v) && isset($v['value'])) {
                            return $v['value'];
                            }
                        else
                            return $v;
                        }
                    $res[] = $value;
                    }
                }
            }
        return $res;
        }

    public function condition($request = null, $withauth = true)
        {
        if ($request == null) {
            $request = request();
            }
        if ($request->has("code")) {
            $this->whereCode($request->code);
            }
        if ($request->has("name")) {
            $this->whereName($request->name);
            }
        if ($request->has("id")) {
            $this->whereId($request->id);
            }
        if ($request->has('filter')) {
            array_map(function ($value)
                {

                if (is_string($value))
                    $value = json_decode($value, true);

                if ($value == null || count($value) == 0) {
                    return;
                    }

                foreach ($value as $k => $v) {
                    $field = $k;
                    if (!is_array($v)) {
                        $buf          = [];
                        $buf['key']   = $k;
                        $buf['value'] = $v;
                        $buf['type']  = 'eq';
                        $value[$k]    = $buf;
                        }
                    else {
                        if (isset($v['filterfield']) && $v['filterfield'] != null && $v['filterfield'] !== "") {
                            $field = $v['filterfield'];
                            }
                        if ($k != 'fuzzy')
                            if (!isset($v['type']) || isEmpty($v['type'])) {
                                $value[$k]['type']  = 'bt';
                                $value[$k]['value'] = $v;
                                }
                        }
                    $value[$k]['key'] = $field;
                    }
                array_map(
                    function ($item)
                        {
                        $this->defaultCondition($item['key'], $item['value'], $item['type'] ?? null, $item['whereType'] ?? "whereHas");
                        },
                    $value
                );
                }, $request->filter);

            }

        $withauth && $this->auth_data_rolewhere();
        return $this;
        }

    private function defaultCondition($key, $val, $type, $whereType = 'whereHas')
        {
        if ($key == 'color_revision.ismy') {
            if ($val == 1)
                $this->whereHas("color_revision");
            else
                $this->whereDoesntHave("color_revision");
            }
        else if ($key == 'fuzzy')
            $this->fuzzySearch($val);
        else
            $this->arrayQurey($key, $val, $type, $this, $whereType);
        }
    public function fuzzySearch($value)
        {
        return $this;
        }
    public function arrayQurey($key, $value, $type, $query, $whereType = 'whereHas')
        {
        $fieldsArray = explode(".", $key);
        // if (is_array($value) || trim($value) != "") 存在field<>''
        return $this->withRelatQurey($fieldsArray, $value, $type, $query, $whereType);
        }

    public function withRelatQurey($array, $value, $filter, $query, $whereType = 'whereHas')
        {
        if (count($array) == 0)
            fail("查询条件错误！");

        $relation = $array[0];
        unset($array[0]);
        $array = array_values($array);
        if (count($array) == 0) {
            return $this->setQureySearch($relation, $value, $filter, $query);
            }
        return $query->{$whereType}($relation, function ($que) use ($array, $value, $filter)
            {

            $this->withRelatQurey($array, $value, $filter, $que);
            });
        }

    public function setQureySearch($field, $value, $filter, $query)
        {
        if (is_string($value)) {
            $value = trim($value);
            }
        switch ($filter) {
            case 'bt':
                $query->whereBetween($field, $value);
                break;
            case 'lk':
                $query->where($field, "like", "%{$value}%");
                break;
            case 'lkr':
                $query->where($field, "like", "{$value}%");
                break;
            case 'lkl':
                $query->where($field, "like", "%{$value}");
                break;
            case 'nl':
                $query->where($field, "not like", "%{$value}%");
                break;
            case 'nlr':
                $query->where($field, "not like", "{$value}%");
            case 'nll':
                $query->where($field, "not like", "%{$value}");
                break;
            case 'in':
                $query->whereIn($field, $value);
                break;
            case 'ni':
                $query->whereNotIn($field, $value);
                break;
            case 'le':
                $query->where($field, "<=", $value);
                break;
            case 'lt':
                $query->where($field, "<", $value);
                break;
            case 'ge':
                $query->where($field, ">=", $value);
                break;
            case 'gt':
                $query->where($field, ">", $value);
                break;
            case 'ne':
                $query->where($field, "<>", $value);
                break;
            case 'eq':
            case '':
                $query->where($field, $value);
                break;
            case 'DESC':
            case 'desc':
                $query->orderBy($field, "DESC");
                break;
            case 'ASC':
            case 'asc':
                $query->orderBy($field, "ASC");
                break;
            }
        return $query;
        }
    /**
     * @param $ids 一对多的明细ID，
     * @param $fk_id 中间表对应一对多的主表的ID值
     * @param $midModel 中间表模型
     * @param $keys 一对多的  多的字段名，
     * @param $key 一对多，一的字段名
     */
    public function saveManyToMany($ids, $fk_id, $midModel, $keys = 'menu_id', $key = "role_id", $remove_other = true)
        {
        $res_ids = [];
        foreach ($ids as $id) {
            if (is_array($id))
                $vid = $id['id'];
            else
                $vid = $id;
            $data = [$keys => $vid, $key => $fk_id];

            $role_data = $midModel::FirstOrCreate($data, $data);

            $res_ids[] = $role_data->id;
            }
        if ($remove_other)
            $midModel::whereNotIn("id", $res_ids)->where($key, "=", $fk_id)->get()->filter(function ($v)
                {
                $v->delete();
                });
        return $res_ids;
        }

    /**
     * 只获取relation 数组
     * @param string $retate_name 关系名称
     * @param  array|callable $where 主约束查询
     * @param callable $relaction_callback 关系约束查询
     * @return Repositories
     * $relaction_callback关系约束查询,放在$where 也可以
     * 例如：getRelatedData("relation",[['relation.name','haha']]);
     * 等同于：getRelatedData("relation",null,function($q){
     *              $q->where("name",'haha');
     *          });
     */
    public function buildWhere($where = null)
        {

        if ($where != null) {
            if (is_callable($where)) {
                $where($this);
                }
            else
                foreach ($where as $v) {
                    $this->setQureySearch($v[0], $v[1], isset($v[2]) ? $v[2] : "eq", $this);
                    }
            }
        return $this;
        }
    public function getRelatedData($retate_name, $where = null, $relaction_callback = null)
        {

        $this->buildWhere($where);
        $data = [];
        $this
            ->with([
                $retate_name => function ($q) use ($relaction_callback)
                    {
                    if ($relaction_callback != null)
                        $relaction_callback($q);
                    }
            ])
            ->get()->filter(function ($v) use ($retate_name, &$data)
                {
                $v->$retate_name->filter(
                    function ($vv) use (&$data)
                        {
                        $data[] = $vv->toArray();
                        }
                );
                });

        return new Collection($data);
        }
    //relation 排序 只支持一级relation排序
    public function OverOrderBy($sort, $order, $query)
        {
        $fieldsArray = explode(".", $sort);
        if (count($fieldsArray) > 1) {
            $sort = $fieldsArray[0] . "_max_" . $fieldsArray[1];
            $this->withMax($fieldsArray[0], $fieldsArray[1]);
            }
        $this->arrayQurey($sort, 'notempty', $order, $query);
        return $this;
        }
    /**
     * 数据权限
     * @return static
     * @author sunkaiyuan
     * 例如 location.department_id;oldlocation.department_id 表示符合这两个的都能看到
     * 构成php：
     *          $this->where(function($query){
     *              $query->orWhere(function($query){
     *                      $query->whereHas('location',fu ($q)=>$q->where(department_id,USER_DEPT_ID))
     *              });
     *              $query->orWhere(function($query){
     *                      $query->whereHas('oldlocation',fu ($q)=>$q->where(department_id,USER_DEPT_ID))
     *              })
     *          })
     */

    private function auth_data_rolewhere()
        {
        $api  = getApi();
        $user = auth()->user();
        if ($api && $user)
            if ($api->is_data_role == 1) {
                //超级管理员跳过
                if ($user->id == 1)
                    return $this;
                $this->where(function ($query) use ($api, $user)
                    {
                    //location.department_id;oldlocation.department_id  这样的拆分
                    foreach (explode(";", $api->department_field) as $field)
                        $query->orWhere(function ($query) use ($user, $field)
                            {
                            //role的部门权限
                            $department_ids = [0];
                            // dd($user->role()->with("department")->get());
                            $user->role->pluck("department")->filter(function ($v) use (&$department_ids)
                                {
                                $v->filter(function ($vv) use (&$department_ids)
                                    {
                                    $department_ids[] = $vv->id;
                                    });
                                });
                            $this->arrayQurey($field, $user->role->pluck("department")[0]->pluck("id")->toArray(), "in", $query);
                            });
                    });
                }
        return $this;
        }
    public function getOne()
        {
        $this->relation();
        return $this->first();
        }
    public function getList()
        {
        $this->relation();
        return $this->get();
        }
    public function getGrid($needSort = true, $sort = null, $order = null, $addSUM = TRUE)
        {
        $request = request();
        //加载关系
        if (!$request->has("table_id"))
            $this->relation();
        $query = $this->getBuilder();

        $page     = $request->page;
        $pageSize = $request->pageSize;
        $sums     = $request->sums;
        $sort     = $sort ?? $request->sort ?? "id";
        $order    = $order ?? $request->order ?? "desc";

        $pageSize = $pageSize < 0 ? 999 : ($pageSize === null ? 40 : $pageSize);

        $page = $page <= 0 ? 1 : $page;

        //保存状态
        if ($pageSize <= 10000)
            $data['total'] = $query->count();
        $sumfile = [];
        if ($sums && $pageSize <= 10000) {
            $clone_query = clone $query;
            foreach ($sums as $v) {
                if ($addSUM) {
                    $array_re = explode(".", $v);
                    if (count($array_re) == 1) {
                        $clone_query->addSelect(DB::raw("{$v}"));
                        }
                    else {
                        $relation = $this->model->{$array_re[0]}();
                        if ($relation instanceof BelongsTo) {
                            $o_key = $relation->getOwnerKeyName();
                            $f_key = $relation->getForeignKeyName();
                            }
                        else {
                            $o_key = $relation->getForeignKeyName();
                            $f_key = $relation->getLocalKeyName();
                            }
                        $model = $relation->getModel();
                        $table = $model->getTable();
                        $clone_query->addSelect(DB::raw("(select sum({$array_re[1]}) from {$table} {$array_re[1]} where {$array_re[1]}.{$o_key}=" . $this->model->getTable() . ".{$f_key})  as '{$v}'"));
                        }
                    }
                $sumfile[] = "sum(`" . $v . "`) as '{$v}'";
                }
            $bindings = $clone_query->getBindings();
            $bindings =
                array_map(function ($v)
                    {
                    return "'{$v}'";
                    }, $bindings);
            $sql      = str_replace('?', '%s', $clone_query->toSql());

            $data['sums'] = DB::select("SELECT " . implode(",", $sumfile) . " FROM (" . sprintf($sql, ...$bindings) . ") a")[0];
            }

        if ($request->has("table_id")) {
            $this->getFieldByTable($request->table_id, $query);
            }
        if (is_callable($needSort)) {
            $needSort($query);
            }
        if ($needSort == true && $sort)
            $this->OverOrderBy($sort, $order, $query);

        $data['rows'] = $query->forPage($page, $pageSize)->get();

        $this->_env_builder = NULL;
        $data['page']       = $page;
        $data['pageSize']   = $pageSize;

        return $data;
        }
    public function getFieldByTable($table_id, $query)
        {
        $fields       = TableColumn::whereTable_id($table_id)->whereLimitget(0)->get()->pluck("field")->map(fn($v) => explode(".", $v));
        $array_fields = [];
        foreach ($fields as $v)
            $this->createMultiArray($v, $array_fields);
        $this->findWithRelation($array_fields, $query);

        }

    public function createMultiArray($segments, &$array_fields = [])
        {
        $segment = array_shift($segments);

        if (!isset($array_fields[$segment])) {
            $array_fields[$segment] = [];
            }
        if (count($segments) > 0) {
            $this->createMultiArray($segments, $array_fields[$segment]);
            }
        else {
            $array_fields[$segment] = $segment;
            }
        return $array_fields;
        }
    public function findWithRelation($array_fields, $query)
        {
        $model = $query->getModel();
        //不是数组直接退出
        if (!is_array($array_fields)) {
            return;
            }
        foreach ($array_fields as $key => $array) {
            if (isEmpty($array)) {
                continue;
                }
            if (method_exists($model, $key)) {
                //不加这个显示不出来 
                $relation = $model->$key();
                if ($relation instanceof BelongsTo) {
                    $o_key = $relation->getOwnerKeyName();
                    $f_key = $relation->getForeignKeyName();
                    }
                else {
                    $o_key = $relation->getForeignKeyName();
                    $f_key = $relation->getLocalKeyName();
                    }

                $query->addSelect($f_key);

                $query->with($key, function ($que) use ($array, $key, $o_key)
                    {
                    if (!is_string($array) || $array != $key) {
                        $que->addSelect($o_key);
                        $this->findWithRelation($array, $que);
                        }
                    });

                }
            else {
                if ($array == $key)
                    $query->addSelect($array);
                }

            }
        }
    /**
     * 自动保持 function
     *
     * @param [type] $data  保存的数据，包括hasMany关系数据
     * @param bool $withSort hasMany数据是否需要排序
     * @param array|string $relations 需要保存的hasMany数据，否则不保存
     * @return Model
     */
    //和Model save 方法冲突
    public function autosave($data = null, $withSort = false, $relations = ['processes', 'details', "extra_cost_details", 'columns', 'buttons', 'forms', 'reports', 'carry', 'car', 'process_dept', 'raws', 'packs'])
        {
        $data         = $data ?? request();
        $relationData = new Collection();
        //附件
        $attachments = null;
        $data        = getArrayableItems($data);
        $relations   = is_string($relations) ? [$relations] : $relations;
        // if ($key == 'company')
        $data = array_filter($data, function ($item, $key) use (&$relationData, &$attachments, $relations)
            {
            if ($item === null) { //&& in_array($key, $this->relation_models)
                return false;
                }
            $item = getArrayableItems($item);
            //过滤附件
            if ($key == 'attachments' && is_array($item)) {
                $attachments = array_map(
                    function ($attachment)
                        {
                        return $attachment['id'];
                        }
                    ,
                    $item
                );
                return false;
                }
            else if (is_array($item)) {
                //需要保存的hasMany 关系才保存
                if (in_array($key, $relations)) {
                    $relationData[$key] = $item;
                    }
                return false;
                }
            //为null,并且时关系模型时，删除
            if ($item === null && in_array($key, $this->relation_models)) {
                return false;
                }

            return true;
            }, 1);

        $id = is_numeric($data['id'] ?? "") ? $data['id'] : 0;

        unset($data['id']);

        $data['updated_at'] = date('Y-m-d H:i:s');


        $model = $this->updateOrCreate(['id' => $id], $data);
        // 保存附件如果有的话

        $this->saveAttachment($attachments, $model);

        $relationData->filter(function ($item, $key) use ($model, $withSort)
            {
            $this->saveRelation($key, $item, $model, $withSort);
            });

        return $model;
        }
    public function saveRelation($name, $item, $model, $withSort = false)
        {
        $relationModel = $model->$name();
        //HasMany 才保存明细
        if ($relationModel instanceof HasMany)
            return $this->saveHasMany($relationModel, $item, $relationModel->getParentKey(), $withSort);
        if ($relationModel instanceof BelongsTo)
            return $this->saveBelongsTo($relationModel, $item, $model);
        return [];
        }
    public function saveBelongsTo($relation, $data, $model)
        {
        //carry_id
        $foreignKeyName = $relation->getForeignKeyName();

        $id = isset($data['id']) && !isEmpty($data['id']) && is_numeric($data['id']) ? $data['id'] : 0;

        $data = array_filter($data ?? [], function ($v)
            {
            return !is_array($v) && $v != null;
            });
        if (count($data) > 0) {
            $model->{$foreignKeyName} = $relation->getModel()->updateOrCreate(['id' => $id], $data)->id;
            $model->save();
            }

        return $model;
        }
    public function deleteAttachment($model)
        {
        App::make(AttachmentRepository::class)->autodelete(function ($query) use ($model)
            {
            $attachmentkey = $model->getAttachmentkey();
            $query->where("source_model", $model::class);
            $query->where("source_key", $attachmentkey);
            $query->where("source_value", $model->{$attachmentkey});
            ;
            });
        return $model;
        }
    //保存附件
    public function saveAttachment($ids, $model)
        {
        if ($ids === null) {
            return;
            }
        $attachmentkey = $model->getAttachmentkey();
        if (!isset($model[$attachmentkey])) {
            fail($model::class . "没有设置attachmentkey字段!请与管理员联系");
            }
        $model->attachment = 0;
        $attR              = App::make(AttachmentRepository::class);
        $newAttachmentIds  = $attR->whereIn("id", array_unique($ids))->get()->map(function ($v) use ($model, $attachmentkey)
            {
            //发现已经有了源模型，说明 是已经使用的附件，复制
            if (
                isNotEmpty($v->source_model) &&
                ($v->source_model != $model::class ||
                    $v->source_key != $attachmentkey ||
                    $v->source_value != $model->{$attachmentkey})
            ) {
                $model->attachment += 1;

                return $this->copyAttachment($v, $model, $attachmentkey);
                }
            //源模型没有用，说明是新传的附件。直接保存 
            else if (
                isEmpty($v->source_model)
            ) {
                $v->source_model = $model::class;
                $v->source_key   = $attachmentkey;
                $v->source_value = $model->{$attachmentkey};
                $v->save();
                $model->attachment += 1;
                return $v->id;
                }
            //没改，说明 这个不用动
            return $v->id;
            });
        //删除附件
        $attR->autodelete(function ($query) use ($newAttachmentIds, $model, $attachmentkey)
            {
            $query->where("source_model", $model::class);
            $query->where("source_key", $attachmentkey);
            $query->where("source_value", $model->{$attachmentkey});
            $query->whereNotIn("id", $newAttachmentIds);
            });

        return $model->save();
        }

    //复制附件
    public function copyAttachment($attachment, $model, $attachmentkey)
        {
        $attachment = $attachment->toArray();
        unset($attachment['id'], $attachment['url'], $attachment['thumb_url']);
        $cpfile               = (new Attachment($attachment));
        $cpfile->source_model = $model::class;
        $cpfile->source_key   = $attachmentkey;
        $cpfile->source_value = $model->{$attachmentkey};
        $cpfile->save();
        return $cpfile->id;
        }

    //删除时，自动删除关系
    public function autodelete($where = null)
        {

        if ($where != null) {
            if (is_callable($where)) {
                $where($this);
                }
            else
                if (is_array($where)) {
                    if (is_array($where[0]))
                        $this->buildWhere($where);
                    else
                        $this->whereIn("id", $where);
                    }
                else
                    $this->whereId($where);
            }

        return $this->get()->filter(function ($item)
            {
            //采用with 后，自动删除with 中的关系
            array_filter(
                $item->getRelations(),
                function ($relation)
                    {
                    if ($relation instanceof Model) {
                        $relation->delete();
                        }
                    else
                        $relation->filter(
                            function ($v)
                                {
                                $v->delete();
                                }
                        );
                    }
            );
            $item->delete();
            return true;
            });
        }
    //保存明细
    public function saveHasMany($relation, $items, $fk_id, $withSort = false)
        {
        $itemCollection = new Collection($items);
        $foreignKey     = $relation->getForeignKeyName();
        $ids            = [0];
        /**
         * 获取父树形ID
         *  #items: array:1 [
         *      "id120" => null
         *      ]
         */

        $parentKey = $itemCollection
            ->where("parent_id", "!=", "0")
            ->where("parent_id", "!=", null)
            ->pluck('', "parent_id");
        if ($parentKey->count() > 0) {
            $itemCollection = $itemCollection->sortBy("parent_id");
            }
        $MODEL = $relation->getModel();
        $itemCollection->filter(function ($item, $key) use ($fk_id, $foreignKey, $MODEL, &$ids, $withSort, $parentKey)
            {

            $item = collect($item)->filter(
                function ($v, $k) use ($MODEL)
                    {
                    //数组去除，如果不是数组，是null，也有可能是关系
                    return !is_array($v) && !(method_exists($MODEL, $k));
                    }
            );

            $defultId = 0;
            $vid      = is_numeric($item['id'] ?? "") ? $item['id'] : 0;

            //找到父关系的ID
            if (isset($item['parent_id'])) {
                //子存在父，从父中找到新的ID
                $item['parent_id'] = $parentKey->has($item['parent_id']) ? $parentKey[$item['parent_id']] : 0;
                $defultId          = isset($item['id']) ? $item['id'] : 0;
                }
            unset($item['id']);
            if ($withSort)
                $item['sort'] = $key;

            //根据表列过滤值！去掉不需要的
            $item              = $this->initializeFieldsData(getArrayableItems($item), $MODEL);
            $item[$foreignKey] = $fk_id;

            $ids[] = $vid = $MODEL->updateOrCreate(['id' => $vid], $item)->id;

            //父ID 存在,保存当前父ID的值
            if ($defultId != 0 && $parentKey->has($defultId)) {
                $parentKey[$defultId] = $vid;
                }
            });

        $MODEL->where($foreignKey, $fk_id)->whereNotIn('id', $ids)->get()->filter(function ($item)
            {
            $item->delete();
            });
        return $ids;
        }
    public function fieldSave($data)
        {
        $data = $this->initializeFieldsData(getArrayableItems($data));
        unset($data['id']);
        return $this->autosave($data);
        }
    public function initializeFieldsData(array $data, $model = null)
        {
        $columns = Schema::getColumnListing(($model ?? $this->model)->table);
        //根据字段过滤
        return array_filter($data, function ($key) use ($columns)
            {
            return in_array($key, $columns);
            }, ARRAY_FILTER_USE_KEY);
        }


    }